<?php
namespace app\api\controller;

use app\common\model\CustomerModel;
use app\common\model\JobModel;
use app\common\model\JobOperationRecordModel;
use app\common\model\JobTypeModel;
use app\common\service\FinanceService;
use app\common\service\NoticeService;
use app\index\model\UserModel;
use think\admin\model\SystemFile;
use think\facade\Db;

/**
 * Class Index
 * @package app\index\controller
 */
class Job extends Base
{


    public function __construct(\think\App $app)
    {
        parent::__construct($app);
    }



    public function getList(){
        $this->checkUserLogin();
        $job = new JobModel();
        
        $pageSize = input('pageSize', 20, 'intval');
        $pageNo = input('pageNo', 1, 'intval');
        $status = input('status', 0, 'intval');
        $job = $job->alias('job')->field('job.*');
        $map = [];
        if($this->checkIsAdmin() == false){
            $map['job.boyi_to_uid'] = $this->user['id']; // 非管理员只看排给自己的任务
        }
        if($status){
            $map['job.status'] = $status;
        }
        $job = $job->where($map)->join("boyi_job_type jt", "jt.id = job_type_id")->field('job.*, jt.name,jt.short_name');
        
        $result = $this->_query($job->order('id desc')->with(['job_add_user', 'job_exec_user', 'customer']))->like("u.name#name",'', input())->page($pageNo, false, false, $pageSize);
        return $this->returnSuccess($result);
    }


    public function getDetail(){
        $this->checkUserLogin();
        $job = new JobModel();

        $job_id = input('job_id', 0, 'intval');
        if(!$job_id){
            return $this->returnError([], "任务ID不能为空");
        }

        $job = $job->alias('job')->field('job.*');
        $map = [];
        $map[] = ['job.id', '=', $job_id];

        $job = $job->where($map)->join("boyi_job_type jt", "jt.id = job_type_id")->field('job.*, jt.name,jt.short_name');
        $result = $job->with(['job_add_user', 'job_exec_user', 'customer'])->find();
        return $this->returnSuccess($result);
    }


    // 获取任务详情
    public function getJobInfo(){
        $this->checkUserLogin();
        $job = new JobModel();
        $job_id = input('job_id', 0, 'intval');

        if(!$job_id){
            return $this->returnError([], "任务ID不能为空");
        }
        $job = $job->alias('job')->join("boyi_job_type jt", "jt.id = job_type_id")->field('job.*, jt.name,jt.short_name')->append(['job_status_info', 'died_line_info'])->with(['job_add_user', 'job_exec_user'])->find($job_id);
        if(!$job){
            return $this->returnError([], "任务不存在");
        }
        $job['customer'] = $job['customer']->append(['died_line_info'])->toArray();
        $job['file_list'] = SystemFile::whereIn('id', explode(',', $job['file_id_list']))->field("id,name,xurl")->select()->toArray();
        
        $operate_list = JobOperationRecordModel::alias('a')->join('boyi_users u', 'a.operator_id = u.id')->where(['a.job_id' => $job_id])->field('a.*, u.name as operator_name')->order('id desc')->select()->toArray();

        // 这里要查询每个操作记录的附件信息，我希望能一次查询，最后在重新匹配到列表中
        $file_id_list = [];
        foreach ($operate_list as &$operate) {
            $file_id_list = array_merge($file_id_list, explode(',', $operate['operation_file']));
        }

        // dump($file_id_list);
        // 这里批量匹配文件到操作记录中
        if($file_id_list){
            $file_list = SystemFile::whereIn('id', $file_id_list)->field("id,name,xurl")->select()->toArray();
            $file_list = array_combine(array_column($file_list, 'id'), $file_list);
            foreach ($operate_list as &$operate) {
                $operate['file_list'] = [];
                $operate_file_id_list = explode(',', $operate['operation_file']);
                foreach ($operate_file_id_list as $file_id) {
                    if(isset($file_list[$file_id])){
                        $operate['file_list'][] = $file_list[$file_id];
                    }
                }
            }
        }
        $job['operate_list'] = $operate_list;
        return $this->returnSuccess($job);
    }

    public function getJobFileList(){
        $this->checkUserLogin();
        $job = new JobModel();
        $job_id = input('job_id', 0, 'intval');

        if(!$job_id){
            return $this->returnError([], "任务ID不能为空");
        }
        $job = $job->find($job_id);
        $result = [];
        if($job){
            $result = SystemFile::whereIn('id', explode(',', $job['file_id_list']))->field("id,name,xurl")->select()->toArray();
        }
        return $this->returnSuccess($result);
    }



    // 统一的任务处理入口
    public function handleJob(){
        $this->checkUserLogin();
        $operation_file = input('operation_file', '', 'string');
        $operation_note = input('operation_note', '', 'string');
        $clue = input('clue', '', 'string');
        $examine_status = input('examine_status', 0, 'intval'); // 审核的结果。 1 通过 2 不通过
        $job = new JobModel();
        $job_id = input('job_id', 0, 'intval');

        if(!$job_id){
            return $this->returnError([], "任务ID不能为空");
        }
        $job = $job->alias('job')->join("boyi_job_type jt", "jt.id = job_type_id")->field('job.*, jt.name,jt.short_name')->find($job_id);
        if(!$job){
            return $this->returnError([], "任务不存在");
        }

        // 判断是否为任务执行人
        if($job['boyi_to_uid'] != $this->user['id'] && $job['boyi_uid'] != $this->user['id']){
            return $this->returnError([], "您不是任务执行人或任务发布人，无法处理该任务");
        }

        $boyi_user = UserModel::find($job['boyi_uid']);
        $boyi_to_user = UserModel::find($job['boyi_to_uid']);

        $notice_user = null;

        


        Db::startTrans();
        try {
            // 不同的任务状态，不同的任务处理逻辑
            $operation_type = JobOperationRecordModel::OPERATE_TYPE_UNKNOW;
            switch ($job['status']) {
                case JobModel::JOB_WAITE_RECEIVE:
    
                    $notice_user = $boyi_user;
                    $operation_type = JobOperationRecordModel::OPERATE_TYPE_RECEIVE;
                    $job->status = JobModel::JOB_WAITE_HANDLE;
                    break;
                case JobModel::JOB_WAITE_HANDLE: case JobModel::JOB_STATUS_REJECT:
    
                    // 这里判断任务类型如果为选题，那么就要将选题的线索信息更新到客户信息中
                    if($job['job_type_id'] == 1){

                        if(!$clue){
                            return $this->returnError([], "请填写选题信息在提交任务数据");
                        }
                        $customer = CustomerModel::find($job['customer_id']);
                        $customer->clue = $clue;
                        $customer->save();
                    }

                    $notice_user = $boyi_user;
                    $operation_type = JobOperationRecordModel::OPERATE_TYPE_HANDLE;
                    // 任务待执行，任务执行 - 任务执行人上传任务文件。并将任务状态改为等待发布人审核
                    $job->status = JobModel::JOB_WAITE_EXAMINE;

                    break;
                case JobModel::JOB_WAITE_EXAMINE:
                    $notice_user = $boyi_to_user;
                    if($examine_status){
                        if($examine_status == 1){
                            $operation_type = JobOperationRecordModel::OPERATE_TYPE_EXAMINE_SUCCESS;
                            // 任务执行中，标记任务已执行完成。
                            $job->status = JobModel::JOB_STATUS_SUCCESS;
                            // 任务完成时，自动记录佣金到用户账户
                            FinanceService::expense($job['amount'], '任务佣金', "未支付", sprintf("%s-%s", $job['id'], $job['name']), [
                                'customer_id' => $job['customer_id'],
                                'job_id' => $job['id'],
                                'boyi_uid' => $this->user['id'],
                                'to_uid' => $job['boyi_to_uid'],
                            ]);

                            // 客户添加支出记录
                            $customer = CustomerModel::find($job['customer_id']);
                            $customer->payout_amount = $customer->payout_amount + $job['amount'];
                            $customer->save();
                        }elseif($examine_status == 2){ // 任务被驳回
                            // 任务执行中，标记任务已作废。
                            $operation_type = JobOperationRecordModel::OPERATE_TYPE_EXAMINE_FAIL;
                            $job->status = JobModel::JOB_STATUS_REJECT;
                        }
                    }else{
                        return $this->returnError([], "审核任务状态有误");
                    }
                    break;
                default:
                    return $this->returnError([], "任务状态有误");
                    break;
            }
            $job->type_status = $job->job_type_id . '-' . $job->status;
            $job->save();
            // 插入任务执行记录
            $record = new JobOperationRecordModel();
            $record->job_id = $job_id;
            $record->operator_id = $this->user['id'];
            $record->operation_type = $operation_type;
            $record->operation_file = $operation_file;
            $record->operation_note = $operation_note;
            $record->save();
            Db::commit();
        } catch (\Exception $e) {
            //throw $th;
            Db::rollback();
            return $this->returnError([], sprintf("任务处理失败, 请重试 - %s", $e->getMessage()));
        }

        $message = "任务处理成功";
        $data = [];
        try {
            // 最后发送任务通知
            if($notice_user){
                $noticeService = new NoticeService($notice_user);
                $data = $noticeService->noticeJobHandle($job, $operation_note);
            }
            //code...
        } catch (\Exception $e) {
            $data = $e->getTrace();
            $message = $e->getMessage();
        }
        $data['notice_user'] = $notice_user;

        return $this->returnSuccess($data, $message);
    }


    public function doEdit(){
        $this->checkUserLogin();
        $job_id = input('id', 0, 'intval');
        $boyi_to_uid = input('boyi_to_uid', 0, 'intval');
        $diedline = input('diedline', '', 'string');
        $amount = input('amount', 0, 'intval');
        $remark = input('remark', '', 'string');
        $file_id_list = input('file_id_list', []);

        if(!$job_id){
            return $this->returnError([], "任务ID有误");
        }

        if(!$boyi_to_uid){
            return $this->returnError([], "任务执行人不能为空");
        }
        if(!$diedline){
            return $this->returnError([], "任务截止日期不能为空");
        }
        if(!$amount){
            return $this->returnError([], "任务佣金不能为空");
        }

        $job = new JobModel();
        $job = $job->find($job_id);
        if(!$job){
            return $this->returnError([], "任务不存在");
        }

        // 任务已完成。不可修改
        if($job['status'] == JobModel::JOB_STATUS_SUCCESS){
            return $this->returnError([], "任务已完成，不可修改");
        }
    
        // 判断是否为任务发布人
        if($job['boyi_uid'] != $this->user['id']){
            return $this->returnError([], "您不是任务发布人，无法修改该任务");
        }
        $job->boyi_to_uid = $boyi_to_uid;
        $job->diedline = strtotime($diedline);
        $job->amount = $amount;
        $job->remark = $remark;
        $job->file_id_list = implode(',', $file_id_list);
        $job->save();
        return $this->returnSuccess([], "任务修改成功");

    }

    public function batchAddUserJob(){
        $this->checkUserLogin();
        $job_json = input('post.job_json');
        $job_arr = json_decode($job_json,true);

        if(!$job_arr){
            return $this->returnError([], "任务数据有误");
        }

        $customer_id = $job_arr[0]['customer_id'] ?? 0;

        if(!$customer_id){
            return $this->returnError([], "任务对应客户数据有误");
        }
        $customer = CustomerModel::find($customer_id);
        if(!$customer){
            return $this->returnError([], "客户数据不存在");
        }

        foreach ($job_arr as $job) {
            if(!isset($job['amount'])){
                return $this->returnError([], "任务佣金设置有误");
            }
            if(!isset($job['customer_id']) || !$job['customer_id']){
                return $this->returnError([], "任务对应客户数据有误");
            }
            if(!isset($job['boyi_to_uid']) || !$job['boyi_to_uid']){
                return $this->returnError([], "任务执行人设置有误");
            }
            if(!isset($job['job_type_id']) || !$job['job_type_id']){
                return $this->returnError([], "任务执行类型有误");
            }
        }

        $job_type_arr = JobTypeModel::whereIn('id',array_column($job_arr,'job_type_id'))->select()->toArray();

        $job_type_arr = array_combine(array_column($job_type_arr,'id'),$job_type_arr);

        $insert_job_arr = [];


        foreach ($job_arr as $job) {
            if(!isset($job_type_arr[$job['job_type_id']])){
                return $this->returnError([], "分配的任务类型不存在");
            }
            $insert_job_arr[] = [
                'boyi_uid' => $this->user['id'],
                'job_type_id' => $job['job_type_id'],
                'customer_id' => $job['customer_id'],
                'boyi_to_uid' => $job['boyi_to_uid'],
                'diedline' => strtotime($job['diedline']),
                'amount' => $job['amount'],
                'remark' => $job['remark'] ?? "",
                'create_time' => time(),
                'update_time' => time(),
                'file_id_list' => implode(',', $job['file_id_list']),
            ];
        }

        $jobModel = new JobModel();


        $boyi_to_uid_list = array_column($insert_job_arr, 'boyi_to_uid');
        $user_list = UserModel::whereIn('id', $boyi_to_uid_list)->select();
        
        $user_list_arr = [];

        foreach ($user_list as $user) {
            $user_list_arr[$user['id']] = $user;
        }
        


        foreach ($insert_job_arr as $job) {
            $jobModel->insert($job);
            $job_id = $jobModel->getLastInsID();

            $job_data = $jobModel->alias('job')->join("boyi_job_type jt", "jt.id = job_type_id")->field('job.*, jt.name,jt.short_name')->find($job_id);
            $noticeService = new NoticeService($user_list_arr[$job['boyi_to_uid']]);
            $result[] = $noticeService->noticeJobHandle($job_data, $job['remark']);
        }


        // $boyi_to_uid_list = array_column($insert_job_arr, 'boyi_to_uid');
        // $to_user_list = UserModel::whereIn('id', $boyi_to_uid_list)->field('id,name, email, userId')->select();
        // $insert_job_arr = array_combine($boyi_to_uid_list, $insert_job_arr);
        
        // // 发送通知
        // $result = [];
        // foreach ($to_user_list as $user) {
        //     $noticeService = new NoticeService($user);
        //     $job_info = $insert_job_arr[$user['id']];
        //     $title = sprintf("您有新的【%s】任务待处理", $job_type_arr[$job_info['job_type_id']]['name']);
        //     $url ="http://boyi.tinyask.cn/#/boyi/job/index";
        //     $content = sprintf(
        //         "客户：%s\n任务佣金：%s\n截止日期：%s\n备注：%s\n\n<a href='%s'>点此查看任务信息</a>", 
        //         $customer['name'], 
        //         $job_info['amount'],
        //         date('Y-m-d', $job_info['diedline']), 
        //         $job_info['remark'], 
        //         $url
        //     );
        //     $noticeService->sendText($title, $content);

        //     $result[$result] = $noticeService->noticeJobHandle($job_info, $job_info['remark']);
        // }

        // 分配任务后进行通知。
        return $this->returnSuccess($result, "任务添加成功");
    
    }


}